import axios from 'axios'
import { message } from 'antd'

const defaultConf = {
    headers: {'Content-Type': 'application/json; charset=UTF-8'},
    timeout: 200000
}

const _request = (params = {}) => {
    return axios({...defaultConf, ...params})
    .then (res => {
        const { result } = res.data

        if (result === 'success') {
            return res.data
        }

        if (result !== 'success') {
            return res.data
        }
    })
    .catch(error => {
        if (String(error).indexOf('200') === -1 && String(error).indexOf('401') > -1 | String(error).indexOf('417') > -1) {
            // window.location.href = `${process.env.REACT_APP_LOGIN}first-login`
            return error
        } else if (String(error).indexOf('403')) {
            return null
        }

        message.error(String(error || '网络错误'))
        return error
    })
}

export default (params) => {
    const type = typeof params

    if (type === 'function') {
        return obj => _request(obj, params)
    }

    if (type === 'object' && type !== null) {
        if (params.method.toUpperCase() === 'POST') {
            let { data } = params
            params.data = JSON.stringify({ token: '123456', ...JSON.parse(data) })
        }
        return _request(params)
    }
}
